﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Castle.Core;
using ClientOverflow.DataTransferObjects;

namespace ClientOverflow.ViewModels.UsersListViewModels
{
    /// <summary>
    /// 
    /// </summary>
    public class UsersListViewModel
    {
        public IEnumerable<UserTagActivityViewModel> Users { get; private set; }

        public UsersListViewModel(Tag tag)
        {
            User[] users;
            using (var serviceClient = ServicesFactory.CreateClientOverflowServiceClient())
            {
                users = serviceClient.GetAllUsers();
                users.SelectMany(user => user.Answers)
                    .ForEach(answer => answer.Question = serviceClient.GetQuestion(answer));
            }

            var userTaggedQuestions = users
                .GroupBy(user => user,
                         user => user.Questions.Where(question => question.Tags.Contains(tag)));
            
            var userTaggedAnswers = users
                .GroupBy(user => user,
                         user => user.Answers.Where(answer => answer.Question.Tags.Contains(tag)));

            var activeUsers =
                userTaggedQuestions.Select(questionsGroup => questionsGroup.Key)
                    .Union(userTaggedAnswers.Select(answersGroup => answersGroup.Key));

            Users = from user in activeUsers
                    join userTaggedQuestion in userTaggedQuestions on user equals userTaggedQuestion.Key
                    join userTaggedAnswer in userTaggedAnswers on user equals userTaggedAnswer.Key
                    select new UserTagActivityViewModel(user, CountTotalVotes(userTaggedQuestion, userTaggedAnswer));


        }

        private int CountTotalVotes(IGrouping<User, IEnumerable<Question>> userTaggedQuestion, IGrouping<User, IEnumerable<Answer>> userTaggedAnswer)
        {
            return userTaggedQuestion.SelectMany(questions => questions)
                       .Sum(question1 => question1.UpVotes.Count - question1.DownVotes.Count) +
                   userTaggedAnswer.SelectMany(answers => answers)
                       .Sum(answer => answer.UpVotes.Count - answer.DownVotes.Count);
        }
    }

    public class UserTagActivityViewModel
    {
        public User User { get; private set; }
        public int Votes { get; private set; }

        public UserTagActivityViewModel(User user, int votes)
        {
            User = user;
            Votes = votes;
        }
    }
}
